package client.comm.baoding.ui.vm

import android.app.Application
import android.net.Uri
import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.comm.commlib.network.data.JsonResult
import client.comm.commlib.network.data.Ret
import client.comm.commlib.out_time
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.Util
import client.comm.baoding.api.bean.PayAccount
import client.comm.baoding.api.bean.UploadRet
import client.comm.baoding.ui.SetSkxxActivity
import client.comm.baoding.ui.viewmodel.MiddleVm
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Response

class SetskxxViewModel(app: Application) : MiddleVm(app) {
    val isShowing = MutableLiveData<Boolean>(false)
    val name = MutableLiveData<String>("支付宝")
    val nameTwo = MutableLiveData<String>("微信")
    val nameThree = MutableLiveData<String>()
    val nameChildBank = MutableLiveData<String>()//支行名称

    val phone = MutableLiveData<String>()
    val phoneFour = MutableLiveData<String>()
    val smscodeOne = MutableLiveData<String>()
    val smscodeTwo = MutableLiveData<String>()
    val smscodeThree = MutableLiveData<String>()
    val smscodeFour = MutableLiveData<String>()


    val realNameOne = MutableLiveData<String>()
    val realNameTwo = MutableLiveData<String>()
    val realNameThree = MutableLiveData<String>()
    val realNameFour = MutableLiveData<String>()


    val payCard = MutableLiveData<String>()
    val payCardTwo = MutableLiveData<String>()
    val payCardThree = MutableLiveData<String>()
    val payCardFour = MutableLiveData<String>()
    val getCodeTxt = MutableLiveData<String>("获取验证码")
    val getCodeEnable = MutableLiveData<Boolean>(true)
    val imgOld = MutableLiveData<String>(null)
    val imgOne = MutableLiveData<Uri>(null)
    val imgTwo = MutableLiveData<Uri>(null)
    val imgTwoOld = MutableLiveData<String>(null)

    val callOne = MutableLiveData<JsonResult<Ret>>()
    val callTwo = MutableLiveData<JsonResult<Ret>>()
    val callThree = MutableLiveData<JsonResult<Ret>>()
    val callFour = MutableLiveData<JsonResult<Ret>>()
    val codeRet = MutableLiveData<JsonResult<Ret>>()
    val dataOne = MutableLiveData<JsonResult<PayAccount>>()
    val dataTwo = MutableLiveData<JsonResult<PayAccount>>()
    val dataThree = MutableLiveData<JsonResult<PayAccount>>()
    val dataFour = MutableLiveData<JsonResult<PayAccount>>()


    fun callOne() {
        hold({
            server.user_pay_account(1)
        }, success = {
            dataOne.value = it
        })
    }

    fun callTwo() {
        hold({
            server.user_pay_account(2)
        }, success = {
            dataTwo.value = it
        })
    }

    fun callThree() {
        hold({
            server.user_pay_account(3)
        }, success = {
            dataThree.value = it
        })
    }

    fun callFour() {
        hold({
            server.user_pay_account(4)
        }, success = {
            dataFour.value = it
        })
    }

    fun ok(aaa: SetSkxxActivity) {

        if (imgOne.value == null && !imgOld.value.isNullOrEmpty()) {

            if (phone.value.isNullOrEmpty()
                || name.value.isNullOrEmpty()
                || payCard.value.isNullOrEmpty()
                || realNameOne.value.isNullOrEmpty()
                || smscodeOne.value.isNullOrEmpty()
            ) {
                toast("所有不得为空")
                return
            }

            hold({
                server.real_names(
                    realNameOne.value!!,
                    "1", name.value!!,"", payCard.value!!, imgOld.value!!,
                    phone.value!!, smscodeOne.value!!
                )
            }, {
                this@SetskxxViewModel.isShowing.value = true
            }, success = {
                callOne.value = it
            }, complete = {
                this@SetskxxViewModel.isShowing.value = false
            })
        } else {
            if (phone.value.isNullOrEmpty()
                || name.value.isNullOrEmpty()
                || payCard.value.isNullOrEmpty()
                || realNameOne.value.isNullOrEmpty()
                || smscodeOne.value.isNullOrEmpty()
                || imgOne.value == null
            ) {
                toast("所有不得为空")
                return
            }
            this@SetskxxViewModel.isShowing.value = true
            viewModelScope.launch {
                flow {

                    var emm: Response<JsonResult<UploadRet>>? = null


                    val file = Util.getLuBan(
                        aaa,
                        this@SetskxxViewModel.imgOne.value!!
                    )
                    val requestFile: RequestBody = RequestBody.create(
                        "multipart/form-data".toMediaTypeOrNull(),
                        file
                    )
                    val body = MultipartBody.Part.createFormData(
                        "file",
                        file.name,
                        requestFile
                    )
                    val descriptionString = "file"
                    val description = RequestBody.create(
                        "multipart/form-data".toMediaTypeOrNull(),
                        descriptionString
                    )
                    out_time {
                        val ret = server.upload(description, body)
                        emm = ret
                    }

                    emit(emm)
                }.map {
                    var emm: JsonResult<Ret>? = null

                    it?.body()?.let {
                        if (it.isSuccess) {
                            out_time {
                                val ret = server.real_names(
                                    realNameOne.value!!,
                                    "1", name.value!!,"", payCard.value!!, it.data!!.url,
                                    phone.value!!, smscodeOne.value!!
                                )
                                emm = ret?.body()
                            }
                        } else {
                            emm = JsonResult<Ret>().apply {
                                message = it.message
                            }
                        }
                    }
                    emm
                }.flowOn(Dispatchers.IO).onCompletion { cause ->
                    this@SetskxxViewModel.isShowing.value = false
                }.catch { cause ->
                    if (cause != null) {
//                        toast(cause.message)
                        toast("网络错误")
                    }
                }
                    .collectLatest {
                        callOne.value = it
                    }
            }

        }

    }

    fun okTwo(aaa: SetSkxxActivity) {

        if (imgTwo.value == null && !imgTwoOld.value.isNullOrEmpty()) {

            if (phone.value.isNullOrEmpty()
                || nameTwo.value.isNullOrEmpty()
                || realNameTwo.value.isNullOrEmpty()
                || smscodeTwo.value.isNullOrEmpty()
                || payCardTwo.value.isNullOrEmpty()
            ) {
                toast("所有不得为空")
                return
            }

            hold({
                server.real_names(
                    realNameTwo.value!!,
                    "2", nameTwo.value!!,"", payCardTwo.value!!, imgTwoOld.value!!,
                    phone.value!!, smscodeTwo.value!!
                )
            }, {
                this@SetskxxViewModel.isShowing.value = true
            }, success = {
                callTwo.value = it
            }, complete = {
                this@SetskxxViewModel.isShowing.value = false
            })
        } else {
            if (phone.value.isNullOrEmpty()
                || nameTwo.value.isNullOrEmpty()
                || realNameTwo.value.isNullOrEmpty()
                || smscodeTwo.value.isNullOrEmpty()
                || payCardTwo.value.isNullOrEmpty()
                || imgTwo.value == null
            ) {
                toast("所有不得为空")
                return
            }
            this@SetskxxViewModel.isShowing.value = true
            viewModelScope.launch {
                flow {
                    var emm: Response<JsonResult<UploadRet>>? = null
                    val file = Util.getLuBan(
                        aaa,
                        this@SetskxxViewModel.imgTwo.value!!
                    )
                    val requestFile: RequestBody = RequestBody.create(
                        "multipart/form-data".toMediaTypeOrNull(),
                        file
                    )
                    val body = MultipartBody.Part.createFormData(
                        "file",
                        file.name,
                        requestFile
                    )
                    val descriptionString = "file"
                    val description = RequestBody.create(
                        "multipart/form-data".toMediaTypeOrNull(),
                        descriptionString
                    )
                    out_time {
                        val ret = server.upload(description, body)
                        emm = ret
                    }
                    emit(emm)
                }.map {
                    var emm: JsonResult<Ret>? = null
                    it?.body()?.let {
                        if (it.isSuccess) {
                            out_time {
                                val ret = server.real_names(
                                    realNameTwo.value!!,
                                    "2", nameTwo.value!!,"", payCardTwo.value!!, it.data!!.url,
                                    phone.value!!, smscodeTwo.value!!
                                )
                                emm = ret?.body()
                            }
                        } else {
                            emm = JsonResult<Ret>().apply {
                                message = it.message
                            }
                        }
                    }
                    emm
                }.flowOn(Dispatchers.IO).onCompletion { cause ->
                    this@SetskxxViewModel.isShowing.value = false
                }.catch { cause ->
                    if (cause != null) {
//                        toast(cause.message)
                        toast("网络错误")
                    }
                }
                    .collectLatest {
                        callTwo.value = it
                    }
            }

        }

    }

    fun okThree() {
        if (phone.value.isNullOrEmpty()
            || nameThree.value.isNullOrEmpty()
            || nameChildBank.value.isNullOrEmpty()
            || realNameThree.value.isNullOrEmpty()
            || smscodeThree.value.isNullOrEmpty()
            || payCardThree.value.isNullOrEmpty()
        ) {
            toast("所有不得为空")
            return
        }
        if (payCardThree.value!!.contains(" ") || payCardThree.value!!.contains("\n")
        ) {
            toast("银行卡不能包含空格")
            return
        }
        hold({
            server.real_names(
                realNameThree.value!!,
                "3", nameThree.value!!,nameChildBank.value!!, payCardThree.value!!, "",
                phone.value!!, smscodeThree.value!!
            )
        }, {
            isShowing.value = true
        }, {
            callThree.value = it
        }, complete = {
            isShowing.value = false
        })
    }

    fun okFour() {
        smscodeFour.value="7788"
        if (phoneFour.value.isNullOrEmpty()
            || realNameFour.value.isNullOrEmpty()
            || smscodeFour.value.isNullOrEmpty()
            || payCardFour.value.isNullOrEmpty()
        ) {
            toast("所有不得为空")
            return
        }
        hold({
            server.real_names(
                realNameFour.value!!,
                "4", "梅兰菊竹交易所","", payCardFour.value!!, "",
                phoneFour.value!!, smscodeFour.value!!
            )
        }, {
            isShowing.value = true
        }, {
            callFour.value = it
        }, complete = {
            isShowing.value = false
        })
    }


    fun getCode() {

        if (TextUtils.isEmpty(phone.value)) {
            toast("手机号不能为空")
            return
        }

        isShowing.value = true
        hold({
            val ts = System.currentTimeMillis()
            server.getcode(
                phone.value!!,
                "${ts}",
                Util.getCaptchaSign(phone.value!!, "${ts}")
            )
        }, {
            getCodeEnable.value = false
            codeRet.value = null
        }, {
            codeRet.value = it
        }, complete = {
            isShowing.value = false
        }, err = {
            getCodeEnable.value = true
        })

    }
}